// function tranListToTreeData1(list, rootValue) {
//   console.time('tranListToTreeData1')
//   const toTree = (value) => {
//     const tree = []
//     list.forEach(item => {
//       if (item.pid === value) {
//         const children = toTree(item.id)
//         item.children = children || []
//         tree.push(item)
//       }
//     })
//     return tree
//   }
//   const tree = toTree(rootValue)
//   const treeMap = list.reduce((map, item) => {
//     return map.set(item.id, item)
//   }, new Map())
//   console.timeEnd('tranListToTreeData1')
//   return {
//     treeMap,
//     tree,
//     list
//   }
// }

export function tranListToTreeData (list, rootValue, option = { key: 'id', parentKey: 'pId' }) {
  const { key, parentKey } = option
  const treePMap = list.reduce((map, item) => {
    if (map.has(item[parentKey])) {
      map.get(item[parentKey]).push(item)
    } else {
      map.set(item[parentKey], [item])
    }
    return map
  }, new Map())

  for (const [, children] of treePMap) {
    children.forEach(v => {
      v.children = treePMap.has(v[key]) ? treePMap.get(v[key]) : []
    })
  }
  const tree = list.filter(v => v[parentKey] === rootValue)
  tree.forEach(v => {
    v.children = treePMap.has(v[key]) ? treePMap.get(v[key]) : []
  })
  const treeMap = list.reduce((map, item) => {
    return map.set(item[key], item)
  }, new Map())
  return {
    tree,
    list,
    treeMap
  }
}
